package com.ayitubie.refuelweb.controller;

import com.ayitubie.refuelweb.config.locale.MessageUtils;
import com.ayitubie.refuelweb.config.response.ResultData;
import com.ayitubie.refuelweb.entity.User;
import com.ayitubie.refuelweb.service.UserServ;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import javax.servlet.http.Cookie;

@RestController
@RequestMapping("/user")
@Api(tags = "用户管理")
@Slf4j
public class UserCtl {
    @Autowired
    UserServ userServ;

    @ApiOperation("用户信息")
    @GetMapping("/getAll")
    public List<User> getAllUser() {
        return userServ.getAllUser();
    }

    @PostMapping("/login")
    public ResultData login(@RequestBody User user,HttpServletResponse response) {
        String token = userServ.login(user.getUserName(),user.getPassword());
        ResultData resultData = new ResultData();
        resultData.setCode(200);
        response.setHeader("content-code","200");
        resultData.setTimestamp(System.currentTimeMillis());
        if (StringUtils.isEmpty(token)) {
            resultData.setCode(500);
            resultData.setData("");
            resultData.setMessage(MessageUtils.get("user.loginError"));
        } else {
            resultData.setData(token);
            resultData.setMessage("");
        }
        return resultData;
    }

    @GetMapping("/getLoginUserInfo")
    public User getLoginUserInfo(String userId) {
        System.out.println(userId);
        return userServ.getUserByUserId(userId);
    }

    @GetMapping("/checkUserExist/{userName}")
    public Boolean checkUserExist(@PathVariable String userName) {
        int count = userServ.checkUserExist(userName);
        return count > 0 ? true : false;
    }


    @PostMapping("/register")
    public ResultData register(@RequestBody User user) {
        userServ.insertUser(user);
        ResultData resultData = new ResultData();
        resultData.setCode(200);
        resultData.setData(user.getUserId() + "");
        resultData.setMessage("");
        return resultData;
    }

    @GetMapping("/setCookie")
    public void setCookie(HttpServletResponse response) {
        Cookie cookie = new Cookie("myCookie", "myValue");
        // 设置为HTTP-only，避免JavaScript访问
        cookie.setHttpOnly(true);
        // 可选：设置Cookie的其他属性，例如过期时间
        // cookie.setMaxAge(3600); // 设置1小时后过期
        // cookie.setSecure(true); // 设置仅在HTTPS下传输
        response.addCookie(cookie);
    }
}
